package com.etime.shycourse.services.coupons.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etime.shycourse.services.coupons.interfaces.PackageimportcourseServices;
import com.etime.shycourse.dao.PackageimportcourseMapper;
import com.etime.shycourse.dto.CouponrangePackageDto;
import com.etime.shycourse.pojo.Packageimportcourse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author wb
 * @since 2022-03-15
 */
@Service
public class PackageimportcourseServiceImpl implements PackageimportcourseServices {
    @Autowired
    private PackageimportcourseMapper mapper;

    /**
     * 保存课程包的课程信息
     * 保存课程包时，会先根据课程包id删除该课程包的所有课程数据，然后再
     * 保存新的课程数据
     *
     * @param packageDto 课程包信息
     * @return 全部保存成功则返回1，否则返回0
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer insertPackageCourse(CouponrangePackageDto packageDto) {
        if (packageDto.getPackageimportcourse ().size () > 0) {
            try {
                // 获取课程包id
                Integer packageid = packageDto.getPackageimportcourse ().get (0).getPackageid ();
                if (packageid != null) {
                    Map<String, Object> map = new HashMap<> ();
                    map.put ("packageid", (int) packageid);
                    // 根据课程包id删除  该课程包的所有课程数据
                    mapper.deleteByMap (map);
                }
                // 再进行保存
                packageDto.getPackageimportcourse ().forEach (l -> {
                    int insert = mapper.insert (l);
                    if (insert == 0) {
                        try {
                            throw new Exception ("创建课程包失败！");
                        } catch (Exception e) {
                            e.printStackTrace ();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace ();
                // @Transactional和try catch捕获异常会让注解失效
                TransactionAspectSupport.currentTransactionStatus ().setRollbackOnly ();
                return 0;
            }
            return 1;
        }
        return 0;
    }

    /**
     * 查询可以用课程包的课程数据初始化
     *
     * @param packageId 课程包的id
     * @return List<Packageimportcourse>
     */
    @Override
    public List<Packageimportcourse> selectCoursePackageList(Integer packageId) {
        return mapper.selectList (new QueryWrapper<Packageimportcourse> ().eq ("packageid", packageId));
    }
}
